#pragma once

#include <iostream>
#include <string>
#include <sstream>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "Util.hpp"

const std::string sep = "\r\n";
const std::string default_root = "./wwwroot";
const std::string home_page = "test/index.html";
const std::string html_404 = "./wwwroot/test/404.html";

class HttpRequest
{
public:
    HttpRequest()
    {
    }
    ~HttpRequest()
    {
    }
    void parse()
    {
        // 1.提取请求行
        std::string line = Util::getOneLine(inbuffer, sep);
        if (line.empty())
            return;
        // 2. 请求行中提取三个字段
        // "请求方法 url http版本"
        std::stringstream ss(line);
        ss >> method >> url >> httpversion;
        // 3. 添加web默认路径
        path = default_root;
        path += url;
        if (path[path.size() - 1] == '/')
        {
            path += home_page;
        }
        // 4.获取资源后缀
        // xxx/yyy/zzz.html  xxx/yyy/zzz.jpg
        auto pos = path.rfind(".");
        if (pos == std::string::npos)
            suffix = ".html";
        else
            suffix = path.substr(pos);
        // 5.获取资源大小
        struct stat st;
        int n = stat(path.c_str(), &st);
        if (n == 0)
        {
            size = st.st_size;
        }
        else
            size = -1;
    }

public:
    std::string inbuffer;
    std::string method;
    std::string url;
    std::string httpversion;
    std::string path;
    std::string suffix;
    int size;
};

class HttpResponse
{
public:
    std::string outbuffer;
};
